package com.lonely.order.support.print.skcsticker;

import cn.hutool.core.util.IdUtil;
import com.lonely.common.exception.BusinessException;
import com.lonely.order.domain.dto.order.SkcStickerQrCodeDTO;
import com.lonely.system.engine.upload.FileUploadFactory;
import com.lonely.system.engine.upload.UploadTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.dromara.pdf.pdfbox.core.base.Document;
import org.dromara.pdf.pdfbox.core.base.Page;
import org.dromara.pdf.pdfbox.handler.PdfHandler;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Objects;

/**
 * @author : 黄志标
 * @date: 2025/10/10 11:39
 * @description: 打印skc贴纸抽象类
 */
@Slf4j
public abstract class AbstractPrintSkcStickerPdfServerImpl implements PrintSkcStickerPdfService {

    /**
     * 打印skc贴纸且上传到MinIO
     *
     * @param skcStickerQrCodes
     * @return
     */
    @Override
    public String pdfAndUploadToMinio(List<SkcStickerQrCodeDTO> skcStickerQrCodes) {
        try (ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream()) {
            Document document = PdfHandler.getDocumentHandler().create();

            // 为每个二维码创建一页
            String lastSizeName = skcStickerQrCodes.get(0).getSizeName();
            for (SkcStickerQrCodeDTO skcStickerQrCode : skcStickerQrCodes) {

                if (!Objects.equals(lastSizeName, skcStickerQrCode.getSizeName())) {
                    // 跟上一个尺码不是同一批的尺码， 添加一个提示页
                    Page tipPage = buildTipPage(document);
                    document.appendPage(tipPage);

                    lastSizeName = skcStickerQrCode.getSizeName();
                }

                // 添加二维码页
                document.appendPage(buildQrCodePage(document, skcStickerQrCode));
            }

            // 保存文档
//            document.saveAndClose("C:\\data\\a.pdf");
//            return "ok";

            document.saveAndClose(pdfOutputStream);

            // 上传到minio
            ByteArrayInputStream pdfFileInputStream = new ByteArrayInputStream(pdfOutputStream.toByteArray());
            String fileName = String.format("%s.pdf", IdUtil.randomUUID());
            String path = FileUploadFactory.getFileUpload(UploadTypeEnum.MINIO).uploadStream(pdfFileInputStream, fileName);
            log.debug("PDF 已成功上传到 MinIO: {}", path);
            return path;
        } catch (Exception e) {
            log.error("生成或上传 PDF 错误: {}", ExceptionUtils.getStackTrace(e));
            throw new BusinessException("生成或上传 PDF 失败");
        }
    }



    /**
     * 构建二维码页
     *
     * @param document
     * @return
     */
    protected abstract Page buildQrCodePage(Document document, SkcStickerQrCodeDTO skcStickerQrCode);

    /**
     * 构建提示页
     *
     * @param document
     * @return
     */
    protected abstract  Page buildTipPage(Document document);

}
